const userrouter = require('./模块化路由.js')
let express = require('express');
let path = require('path')
let fs = require('fs');
let app = express();
app.listen(3000,(req,res)=>{
    console.log('已开启服务器');
})
//资源静态化
app.use('/view',express.static(path.join(__dirname,'view')))
app.get('/login',(req,res)=>{
    res.sendFile(path.join(__dirname,'login.html'))
})

app.use(express.urlencoded({ extended: true }));
app.use(userrouter);
// app.get('/login', (req, res) => {
//     let abc = fs.readFileSync('./login.html', 'utf-8');
//     res.send(abc)
// })
// app.get('/register', (req, res) => {
//     let abc = fs.readFileSync('./register.html', 'utf-8');
//     res.send(abc)
// })
app.post('/dologin', (req, res) => {
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码");
       
        return;
    }
    let data = fs.readFileSync("./persons.json", "utf-8");
    
    let arr = JSON.parse(data);
    let index = arr.findIndex(
        (item) =>
            item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        res.send("用户名或密码错误");
    } else {
        res.send("登录成功");
    }
})
app.post('/doregister', (req, res) => {
    if (req.body.username == "" || req.body.password == "") {
        res.send("请输入用户名或者密码"); 
        return;
    }
   
    let data = fs.readFileSync("./persons.json", "utf-8");
  
    let arr = JSON.parse(data);
    
    let index = arr.findIndex(
        (item) =>
            item.username == req.body.username && item.password == req.body.password
    );
    if (index == -1) {
        arr.push(req.body);
        fs.writeFileSync("./persons.json", JSON.stringify(arr));
        res.send("注册成功");
    } else {
        res.send("当前用户名已存在");
    }
})
